package com.weasel.weixin.commons.session.mgt;

import com.weasel.weixin.commons.session.WeixinSession;
import com.weasel.weixin.commons.session.dao.MemorySessionDAO;
import com.weasel.weixin.commons.session.dao.SessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.Collections;

/**
 * Created by Dylan on 2015/12/8.
 */
public class DefaultWeixinSessionManager extends AbstractWeixinValidatingSessionManager {

    private final static Logger logger = LoggerFactory.getLogger(DefaultWeixinSessionManager.class);

    private SessionDAO sessionDAO;

    private boolean deleteInvalidSession;

    public DefaultWeixinSessionManager() {
        deleteInvalidSession = true;
        this.sessionDAO = new MemorySessionDAO();
    }

    public SessionDAO getSessionDAO() {
        return sessionDAO;
    }

    public void setSessionDAO(SessionDAO sessionDAO) {
        this.sessionDAO = sessionDAO;
    }

    public boolean isDeleteInvalidSession() {
        return deleteInvalidSession;
    }

    public void setDeleteInvalidSession(boolean deleteInvalidSession) {
        this.deleteInvalidSession = deleteInvalidSession;
    }

    @Override
    protected void afterCreateSession(WeixinSession session) {
        sessionDAO.create(session);
    }

    @Override
    protected Collection<WeixinSession> getActiveSessions() {
        Collection<WeixinSession> activeSessions = sessionDAO.list();
        return null != activeSessions ? activeSessions : Collections.EMPTY_SET;
    }

    @Override
    protected WeixinSession doGetSession(String sessionid) {
        return sessionDAO.get(sessionid);
    }

    @Override
    protected void afterStop(WeixinSession session) {
        if(isDeleteInvalidSession()){
            if(logger.isDebugEnabled()){
                logger.debug("session had stoped,remove the session");
            }
            sessionDAO.delete(session.getId());
        }
    }

    @Override
    protected void onChange(WeixinSession session) {
        sessionDAO.update(session);
    }
}
